//
//  TJMerchantInfoController.m
//  BaoDian
//
//  Created by mac on 2024/7/22.
//

#import "TJMerchantInfoController.h"
#import "TJTitleCellButton.h"
#import "TJModifyNameController.h"
#import <Photos/Photos.h>

@interface TJMerchantInfoController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) NSMutableDictionary *buttonPools;
@property (nonatomic, weak) UIImageView *avatarImageView;


@end

@implementation TJMerchantInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationBar.title = @"商家信息";
    
    UIScrollView *scrollView = [UIScrollView addToView:self.view];
    scrollView.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight - TabBarHeight);
    CGSize contentSize = scrollView.bounds.size;
    scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    scrollView.contentSize = contentSize;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.alwaysBounceVertical = YES;
    scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    
    UIView *contentView = [[UIView alloc] init].addTo(scrollView);
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
        make.width.offset(contentSize.width);
        make.height.offset(contentSize.height);
    }];
    
    UIView *infoView = [UIView addToView:contentView];
    infoView.backgroundColor = UIColor.tj_1E1F23Color;
    infoView.addCornerRadius(12);

    TJTitleCellButton *avatarButton = [TJTitleCellButton addToView:infoView];
    [avatarButton addTarget:self action:@selector(didClickAvatarButton) forControlEvents:UIControlEventTouchUpInside];
    [avatarButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.right.offset(0);
        make.height.offset(100);
    }];
    avatarButton.model = [TJCellModel modelWithBlock:^(TJCellModel * _Nonnull model) {
        model.text = @"头像";
        model.identifier = @"avatar";
        model.showArrow = YES;
        model.textFont = UIFontMediumMake(16);
        model.textColor = UIColor.whiteColor;
        [self.buttonPools setObject:avatarButton forKey:model.identifier];
    }];
    
    UIImageView *avatarImageView = [UIImageView addToView:avatarButton];
    [avatarImageView addTapGesturesWithTarget:self action:@selector(didClickAvatarButton)];
    avatarImageView.addCornerRadius(30);
    [avatarImageView tj_setImageWithURL:TJUserInfo.avatar.URL placeholderImage:[UIImage imageNamed:defaultAvatarName]];
    [avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(42);
        make.width.height.offset(60);
        make.centerY.offset(0);
    }];
 
    _avatarImageView = avatarImageView;
    
    TJTitleCellButton *nameButton = [TJTitleCellButton addToView:infoView];
    [nameButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(avatarButton.mas_bottom);
        make.left.right.equalTo(avatarButton);
        make.height.offset(46);
    }];
    nameButton.model = [TJCellModel modelWithBlock:^(TJCellModel * _Nonnull model) {
        model.text = @"商家名称";
        model.identifier = @"name";
        model.showArrow = YES;
        model.detailTextColor = UIColor.whiteColor;
        model.detailTextFont = UIFontMake(16);
        model.textFont = UIFontMediumMake(16);
        model.textColor = UIColor.whiteColor;
        [self.buttonPools setObject:nameButton forKey:model.identifier];
    }];
    
    TJTitleCellButton *IDButton = [TJTitleCellButton addToView:infoView];
    [IDButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nameButton.mas_bottom);
        make.left.right.equalTo(avatarButton);
        make.height.offset(46);
    }];
    IDButton.model = [TJCellModel modelWithBlock:^(TJCellModel * _Nonnull model) {
        model.text = @"用户身份";
        model.identifier = @"Id";
        model.showArrow = NO;
        model.detailText = @"商家";
        model.detailTextColor = UIColor.tj_8D9298Color;
        model.detailTextFont = UIFontMake(16);
        model.textFont = UIFontMediumMake(16);
        model.textColor = UIColor.whiteColor;
        [self.buttonPools setObject:IDButton forKey:model.identifier];
    }];
    
    TJTitleCellButton *userIDButton = [TJTitleCellButton addToView:infoView];
    [userIDButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(IDButton.mas_bottom);
        make.left.right.equalTo(avatarButton);
        make.height.offset(46);
    }];
    userIDButton.model = [TJCellModel modelWithBlock:^(TJCellModel * _Nonnull model) {
        model.text = @"用户ID";
        model.identifier = @"userId";
        model.showArrow = NO;
        model.detailText = @"55552244441";
        model.detailTextColor = UIColor.tj_8D9298Color;
        model.detailTextFont = UIFontMake(16);
        model.textFont = UIFontMediumMake(16);
        model.textColor = UIColor.whiteColor;
        [self.buttonPools setObject:userIDButton forKey:model.identifier];
    }];
    
    TJTitleCellButton *phoneButton = [TJTitleCellButton addToView:infoView];
    [phoneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(userIDButton.mas_bottom);
        make.left.right.equalTo(avatarButton);
        make.height.offset(46);
    }];
    phoneButton.model = [TJCellModel modelWithBlock:^(TJCellModel * _Nonnull model) {
        model.text = @"手机号";
        model.identifier = @"phone";
        model.detailTextFont = UIFontMake(16);
        model.textFont = UIFontMediumMake(16);
        model.textColor = UIColor.whiteColor;
        [self.buttonPools setObject:phoneButton forKey:model.identifier];
    }];
    
    TJTitleCellButton *passwordButton = [TJTitleCellButton addToView:infoView];
    [passwordButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(phoneButton.mas_bottom);
        make.left.right.equalTo(avatarButton);
        make.height.offset(46);
    }];
    passwordButton.model = [TJCellModel modelWithBlock:^(TJCellModel * _Nonnull model) {
        model.text = @"修改登录密码";
        model.identifier = @"password";
        model.showArrow = YES;
        model.detailText = @"去修改";
        model.detailTextColor = UIColor.tj_8D9298Color;
        model.detailTextFont = UIFontMake(16);
        model.textFont = UIFontMediumMake(16);
        model.textColor = UIColor.whiteColor;
        [self.buttonPools setObject:passwordButton forKey:model.identifier];
    }];
    
    [infoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(16);
        make.top.offset(KNavBarHight + 10);
        make.bottom.equalTo(passwordButton.mas_bottom).offset(8);
    }];
    
    [self.buttonPools enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, UIButton *  _Nonnull obj, BOOL * _Nonnull stop) {
        [obj addTarget:self action:@selector(didClickItemButton:) forControlEvents:UIControlEventTouchUpInside];
    }];
    
    dispatch_async_sql_queue(^{
        TJUserModel *userModel = [TJUserModel currentAccountModel];
        dispatch_async_main_queue(^{
            [avatarImageView tj_setImageWithURL:userModel.avatar.URL placeholderImage:[UIImage imageNamed:defaultAvatarName]];
            
            nameButton.model.detailText = userModel.realName;
            [nameButton reloadData];
            
            userIDButton.model.detailText = userModel.Id;
            [userIDButton reloadData];
            
            if (userModel.account) {
                phoneButton.model.detailText = userModel.account;
                phoneButton.model.detailTextColor = UIColor.tj_8D9298Color;
                phoneButton.model.showArrow = NO;
            } else {
                phoneButton.model.detailText = @"去绑定";
                phoneButton.model.detailTextColor = UIColor.tj_8D9298Color;
                phoneButton.model.showArrow = YES;
            }
            [phoneButton reloadData];
        });
    });
}

- (void)didClickItemButton:(TJTitleCellButton *)button {
    TJCellModel *model = button.model;
    if ([model.identifier isEqualToString:@"name"]) {
        TJModifyNameController *modifyNameController = [[TJModifyNameController alloc] init];
        modifyNameController.modalPresentationStyle = UIModalPresentationFullScreen;
        modifyNameController.text = model.detailText;
        [modifyNameController setCompleteBlock:^(NSString * _Nonnull name) {
            TJTitleCellButton *nameButton = [self.buttonPools valueForKey:model.identifier];
            nameButton.model.detailText = name;
            [nameButton reloadData];
 
            if (self.updateInfoBlock) {
                self.updateInfoBlock(2, name);
            }
        }];
        [self presentViewController:modifyNameController animated:YES completion:nil];
        return;
    }
    
    if ([model.identifier isEqualToString:@"password"]) {
        [self.navigationController pushViewControllerWithName:@"TJModifyPasswordController"];
        return;
    }
    
    if ([model.identifier isEqualToString:@"phone"]) {
        if (!model.showArrow) return;
        [self.navigationController pushViewControllerWithName:@"TJBindingPhoneController"];
        return;
    }
 
}

- (void)didClickAvatarButton {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
        [self alertWithTitle:nil message:@"不能访问您的相册，前往开启？".localizedString leftButtonName:@"取消" rightButtonName:@"前往开启".localizedString leftButtonBlock:^{
        } rightButtonBlock:^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        }];
        return;
    }
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = (UIImage *)info[UIImagePickerControllerEditedImage];
    [picker dismissViewControllerAnimated:YES completion:^{
        [self uploadImageWithImage:image];
    }];
}

- (void)uploadImageWithImage:(UIImage *)image {
    
    [TJHUD showLoadingInView:self.view];
        
    [image asynImageSize:CGSizeMake(80, 80) color:UIColor.whiteColor finishiBlock:^(UIImage *drawImage) {
        
        NSString *fileName = getFileNameWithPathExtension(@"jpg");
            
        [TJNetworking.shareNetwork uploadFileWithURL:@"/user/updatePic" fileData:UIImageJPEGRepresentation(drawImage, 0.75) fileKey:@"file" fileName:fileName mimeType:@"image.jpg" parameters:nil success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
            NSLog(@"responseObject %@", responseObject);
            [TJHUD hiddenLoading];
            self.avatarImageView.image = image;
            
            dispatch_async_sql_queue(^{
                TJUserModel *userModel = [TJUserModel currentAccountModel];
                userModel.avatar = data;
                [userModel bg_saveOrUpdate];
            });
            
            if (self.updateInfoBlock) {
                self.updateInfoBlock(1, data);
            }
        } failure:^(NSError * _Nonnull error) {
            [TJHUD showMessage:@"上次失败, 请稍后再试!"];
        }];
    }];
}
 

- (NSMutableDictionary *)buttonPools {
    if (!_buttonPools) {
        _buttonPools = [NSMutableDictionary dictionary];
    }
    return _buttonPools;
}

- (void)reloadData {
    
    
}
 
@end



